package com.by.order.scheduler;

import com.by.common.constant.OrderConstant;
import com.by.order.api.service.IReliableMessageService;
import com.by.order.api.vo.ReliableMessageVo;
import com.by.product.api.service.IProductService;
import com.by.rpc.annotation.RpcReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class MessageTaskScheduler {

    @Autowired
    private IReliableMessageService reliableMessageService;

    @RpcReference(interfaceClass = IProductService.class, version = "1.0.0", group = "default")
    private IProductService productService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String LOCK_KEY = "order:scheduler:lock";
    private static final long LOCK_TIMEOUT_SECONDS = 30; // 锁超时时间，应略大于任务执行时间

    @Scheduled(fixedDelay = 10000, initialDelay = 3000)
    public void processPendingMessages() {
        // 使用 UUID 作为锁的 value，防止误删
        String lockValue = UUID.randomUUID().toString();
        // 1. 获取分布式锁，防止多实例并发执行
        Boolean locked = stringRedisTemplate.opsForValue().setIfAbsent(LOCK_KEY, lockValue, LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS);

        if (Boolean.FALSE.equals(locked)) {
            log.info("未获取到分布式锁，跳过本次任务执行。");
            return;
        }

        try {
            log.info("开始扫描待发送的消息...");
            // 2. 获取待发送的消息列表，使用数据库乐观锁防止其他任务重复处理
            List<ReliableMessageVo> messages = reliableMessageService.getMessagesByStatus(
                    OrderConstant.MESSAGE_STATUS_TO_BE_SENT, 100);

            if (messages.isEmpty()) {
                log.info("没有待发送的消息。");
                return;
            }

            log.info("扫描到 {} 条待发送消息，开始处理。", messages.size());

            for (ReliableMessageVo message : messages) {
                // 增加重试次数的判断，防止无限重试
                if (message.getTryCount() >= OrderConstant.MAX_RETRY_COUNT) {
                    log.warn("消息达到最大重试次数，将消息状态更新为失败并跳过处理。消息ID: {}", message.getMessageId());
                    reliableMessageService.updateMessageStatus(
                            message.getMessageId(),
                            OrderConstant.MESSAGE_STATUS_FAILED,
                            message.getTryCount() + 1
                    );
                    continue;
                }

                try {
                    // 3. 根据消息类型，调用不同的业务服务
                    // 核心：所有RPC服务必须实现幂等性
                    if (OrderConstant.MESSAGE_TYPE_STOCK_DECREASE.equals(message.getMessageType())) {
                        Long orderId = Long.parseLong(message.getBusinessId());
                        // productService.decreaseStock(orderId); 必须是幂等的
                        productService.decreaseStock(orderId);
                    } else if (OrderConstant.MESSAGE_TYPE_STOCK_CONFIRM.equals(message.getMessageType())) {
                        Long orderId = Long.parseLong(message.getBusinessId());
                        productService.confirmStockDeduction(orderId);
                    } else if (OrderConstant.MESSAGE_TYPE_STOCK_ROLLBACK.equals(message.getMessageType())) {
                        Long orderId = Long.parseLong(message.getBusinessId());
                        productService.rollbackStock(orderId);
                    }

                    // 4. 如果RPC调用成功，则更新消息状态为“已发送”
                    reliableMessageService.updateMessageStatus(
                            message.getMessageId(),
                            OrderConstant.MESSAGE_STATUS_SENT,
                            message.getTryCount() + 1
                    );
                    log.info("消息发送成功，消息ID: {}", message.getMessageId());

                } catch (Exception e) {
                    // 5. 如果RPC调用失败，只记录日志，不更新状态为FAILED
                    // 这样下次任务仍能处理
                    log.error("消息发送失败，消息ID: {}，等待下次重试。", message.getMessageId(), e);
                    // 这里可以记录日志，但不需要更新状态，让下一次任务处理
                    // 或者增加指数退避策略，根据重试次数决定下次重试的时间
                }
            }
        } finally {
            // 6. 释放分布式锁
            // 使用 Lua 脚本确保原子性操作，避免误删
            String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
            stringRedisTemplate.execute(new DefaultRedisScript<>(luaScript, Long.class), Collections.singletonList(LOCK_KEY), lockValue);
        }
    }
}